﻿using System.Collections;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using SPContrib.Extensions;

namespace SPContrib.Artifacts.Definitions
{
    /// <summary>
    /// Definition of a File (i.e. files included in module elements) element
    /// </summary>
    public class FileDefinition
    {
        private ModuleDefinition _parent;
        private FileInfo _spfile;

        /// <summary>
        /// Specifies the physical path to the file set relative to the feature
        /// </summary>
        /// <remarks>xml: Path</remarks>
        public string PhysicalPath { get; private set; }
        /// <summary>
        /// A collection of key/value pairs to include with the file to provision, added to the SPFile object
        /// </summary>
        public Hashtable Properties { get; private set; }
        internal FileInfo SPFile
        {
            get
            {
                return this._spfile;
            }
        }
        /// <summary>
        /// Specifies the virtual path for the file
        /// </summary>
        public string VirtualPath { get; private set; }

        public FileDefinition(ModuleDefinition module, XElement file)
        {
            // TODO: add support for .webpart files and manifests together (not sure right now what I intend with that but...)
            this._parent = module;
            this.PhysicalPath = file.Attribute<string>("Path");
            //this.Name = file.Attribute<string>("Url");
            //this.NameAtDestination = file.Attribute<string>("Name");

            Properties = new Hashtable(
                            (from property in file.Elements("Property")
                             select property)
                                .ToDictionary(property => property.Attribute<string>("Name"),
                                              property => property.Attribute<string>("Value")));


            //if (module.HasSourceLocation == false)
            //{
            //    this.Source = new FileInfo(Path.Combine(module.FeaturePath, file.Attribute<string>("Path")));                
            //}
            //else
            //{
            //    this.Source = new FileInfo(Path.Combine(module.FeatureAndSourcePath, this.Name));
            //}

            this._spfile = _parent.FindFileByDefinition(this);

            
        }
    }
}
